package com.atkxp.web;

import com.atkxp.domain.Cart;
import com.atkxp.domain.Order;
import com.atkxp.domain.OrderItem;
import com.atkxp.domain.User;
import com.atkxp.service.OrderService;
import com.atkxp.service.impl.OrderServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author user
 * @declaration
 * @create 2022/10/5-10:36
 */
@WebServlet(name = "OrderServlet", value = "/manager/orderServlet")
public class OrderServlet extends BaseServlet {
    private OrderService orderService = new OrderServiceImpl();

    protected void createOrder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        User user = (User) request.getSession().getAttribute("user");
        if (cart == null) {
            request.getRequestDispatcher("index.jsp").forward(request, response);
            return;
        }
        if (user == null) {
            request.getRequestDispatcher("/pages/user/login.jsp").forward(request, response);
            return;
        }
        int id = user.getId();
        String orderId = orderService.createOrder(cart, id);
        request.getSession().setAttribute("orderId", orderId);
        response.sendRedirect(request.getContextPath() + "/pages/cart/checkout.jsp");
    }

    protected void showAllOrders(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Order> orders = orderService.showAllOrders();
        request.setAttribute("orders", orders);
        request.getRequestDispatcher("/pages/manager/order_manager.jsp").forward(request, response);
    }

    protected void sendOrder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String orderId = request.getParameter("orderId");
        orderService.sendOrder(orderId);
        response.sendRedirect(request.getHeader("Referer"));
    }
    protected void showOrderDetails(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<OrderItem> orderItems = orderService.showOrderDetails(request.getParameter("orderId"));
        request.setAttribute("orderItems", orderItems);
        request.getRequestDispatcher("/pages/order/orderDetail.jsp").forward(request, response);
    }

}

